import logging
import json
import os
import re
from logging.handlers import RotatingFileHandler

# Configure logging
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def setup_logging(log_file_path, max_bytes=10*1024*1024, backup_count=5):
    """设置日志记录"""
    # 确保日志文件所在的目录存在
    log_dir = os.path.dirname(log_file_path)
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 创建一个RotatingFileHandler
    handler = RotatingFileHandler(
        log_file_path,
        maxBytes=max_bytes,
        backupCount=backup_count,
        encoding='utf-8'  # 指定编码
    )
    
    # 设置日志记录格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    
    # 获取根日志记录器并添加处理器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    
    # 防止重复添加处理器
    if not root_logger.handlers:
        root_logger.addHandler(handler)
    
    # 添加一个StreamHandler以将日志输出到控制台
    # stream_handler = logging.StreamHandler()
    # stream_handler.setFormatter(formatter)
    # if not any(isinstance(h, logging.StreamHandler) for h in root_logger.handlers):
    #     root_logger.addHandler(stream_handler)

    return root_logger

def load_settings(settings_file='settings.txt'):
    """从文件中加载设置"""
    if not os.path.exists(settings_file):
        print(f"警告: {settings_file} 文件不存在。")
        return {}
    try:
        with open(settings_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except json.JSONDecodeError:
        print(f"警告: {settings_file} 文件格式不正确，无法解析JSON。")
        return {}
    except Exception as e:
        print(f"加载配置文件时出错: {e}")
        return {}

def get_llm_api_key(settings, model_name):
    """根据模型名称获取API Key"""
    if model_name.startswith("gemini"):
        return settings.get("GEMINI_API_KEY")
    elif model_name.startswith("gpt-"):
        return settings.get("OPENAI_API_KEY")
    elif "deepseek" in model_name:
        return settings.get("DEEPSEEK_API_KEY")
    elif "glm" in model_name or "zhipu" in model_name:
        return settings.get("ZHIPU_API_KEY")
    else:
        return os.environ.get("DEFAULT_API_KEY")

def get_llm_base_url(settings, model_name):
    """根据模型名称获取Base URL"""
    if model_name.startswith("gemini"):
        return settings.get("GEMINI_BASE_URL")
    elif model_name.startswith("gpt-"):
        return settings.get("OPENAI_BASE_URL")
    elif "deepseek" in model_name:
        return settings.get("DEEPSEEK_BASE_URL")
    elif "glm" in model_name or "zhipu" in model_name:
        return settings.get("ZHIPU_BASE_URL")
    else:
        return os.environ.get("DEFAULT_BASE_URL")

def get_model_name(settings, model_type="default"):
    """获取模型名称"""
    return settings.get("MODEL_NAME", "gemini-1.5-flash-latest")

def get_tool_config(settings, tool_name):
    """获取工具配置"""
    return settings.get("TOOL_CONFIGS", {}).get(tool_name, {})

def get_json_from_str(s):
    """从字符串中提取JSON对象"""
    try:
        match = re.search(r'\{.*\}', s, re.DOTALL)
        if match:
            json_str = match.group(0)
            # 尝试解析JSON
            return json.loads(json_str)
        else:
            return None
    except json.JSONDecodeError:
        # 如果解析失败，可以尝试更宽松的解析
        try:
            # 移除结尾的逗号等常见错误
            json_str = json_str.strip()
            if json_str.endswith(','):
                json_str = json_str[:-1]
            return json.loads(json_str)
        except json.JSONDecodeError:
            print("无法从字符串中解析JSON")
            return None
    except Exception as e:
        print(f"提取JSON时发生错误: {e}")
        return None

def print_and_log(message, level=logging.INFO):
    """打印并记录消息"""
    print(message)
    if level == logging.INFO:
        logger.info(message)
    elif level == logging.WARNING:
        logger.warning(message)
    elif level == logging.ERROR:
        logger.error(message)
    elif level == logging.DEBUG:
        logger.debug(message)

def load_chat_history(file_path="memory/chat_history.json"):
    """加载聊天记录"""
    if not os.path.exists(file_path):
        return []
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def save_chat_history(history, file_path="memory/chat_history.json"):
    """保存聊天记录"""
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(history, f, ensure_ascii=False, indent=4)